import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Space, UploadFile } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import {
  proIndicatorInfoAdd,
  proIndicatorInfoImport,
  proIndicatorInfoUpdate
} from '@/services/bizApi/shengchanzhibiaoxinxijiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess: () => void;
};

export type EditTeamRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;

  handleImport: (arg: { onSuccess: () => void; file: UploadFile }) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditTeamRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditTeamRef['open']>[0]>();
  const teamArray = useRef<BIZAPI.ProShiftTeamEntity[]>([]);

  console.log('store.user:', store.user);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        id: args?.type === 'edit' || args?.type === 'add' ? null : args?.rowData?.id || null,
        teamId: values.teamId,
        teamName: teamArray.current.find((item) => item.id === values.teamId)?.name,
        dutyStartTime: dayjs(values.dutyTime[0]).format('YYYY-MM-DD HH:mm:ss'),
        dutyEndTime: dayjs(values.dutyTime[1]).format('YYYY-MM-DD HH:mm:ss'),
        reporterId: store.user?.id,
        reporterName: store.user?.fullName
      };

      if (args?.type === 'edit') {
        await proIndicatorInfoUpdate({
          ...query,
          id: args.rowData.id as number
        });
      } else {
        await proIndicatorInfoAdd(query);
      }

      args?.onSuccess?.();
      setOpen(false);
      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              dutyTime: [dayjs(arg.rowData.dutyStartTime), dayjs(arg.rowData.dutyEndTime)]
            });
          } else {
            form.resetFields();
          }
        });
      },
      handleImport: async (arg) => {
        const formData = new FormData();
        formData.append('file', arg.file.originFileObj!);

        await proIndicatorInfoImport({} as ArgumentsType<typeof proIndicatorInfoImport>[0], {
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData,
          timeout: 60000
        });
        store.app?.message.success('导入成功');
        arg?.onSuccess?.();
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增填报',
          edit: '编辑填报',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item label="填报人">
          <Input disabled defaultValue={store.user?.fullName} />
        </Form.Item>
        <ProFormSelect
          name="teamId"
          label="班组名称"
          placeholder="请选择班组名称"
          rules={[{ required: true, message: '请选择班组名称' }]}
          request={async () => {
            const res = await proShiftTeamPage({
              page: 1,
              size: 1000
            });
            teamArray.current = res.data?.records || [];

            return (
              res.data?.records?.map((item) => ({
                value: item.id,
                label: item.name
              })) || []
            );
          }}
        />
        <Form.Item
          label="值班时间"
          name="dutyTime"
          rules={[
            {
              required: true,
              message: '请选择值班时间'
            }
          ]}
        >
          <DatePicker.RangePicker
            inputReadOnly={true}
            showTime={{
              format: 'HH',
              hideDisabledOptions: true
            }}
            format="YYYY-MM-DD HH:mm:ss"
            style={{ width: '100%' }}
            placeholder={['开始时间', '结束时间']}
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
